﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;

using ProtoImaginer.ProtoProject;
using ProtoImaginer.Models;

namespace ProtoImaginer
{
    public partial class MainPage : PhoneApplicationPage
    {
        public static List<Project> MyProjects = new List<Project>();
        
        public void DeleteSelected(List<Project> list, Guid id)
        {
            foreach(Project pjt in list)
            {
                if (pjt.getId().Equals(id)) { list.Remove(pjt); break; }
            }
        }

        protected Boolean SignedIn = false;

        // Constructor
        public MainPage()
        {

            DispatcherTimer t = new DispatcherTimer();
            t.Interval = TimeSpan.FromSeconds(1);
            t.Tick += OnTimerTick;
            t.Start();
            InitializeComponent();
            // Set the data context of the listbox control to the sample data
            checkSign();
            checkProject();
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            App.ViewModel.LoadData();
        }
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        #region RefreshFunction&Timer
        protected void Refresh()
        {
            App.ViewModel.LoadData();
            //Customized Codes Here
            checkSign();
            checkProject();
        }
        void OnTimerTick(object sender, EventArgs e)
        {
            UpdateClock();
        }

        void UpdateClock()
        {
            Refresh();
        }

        protected void checkProject()
        {
            if (MyProjects.Count() == 0)
            {
                ProjectListBox.Visibility = Visibility.Collapsed;
                NoProjectNotice.Visibility = Visibility.Visible;
            }
            else
            {
                ProjectListBox.Visibility = Visibility.Visible;
                NoProjectNotice.Visibility = Visibility.Collapsed;
            }
        }
        private void checkSign()
        {
            if (!SignedIn)
            {
                SignInText.Visibility = Visibility.Visible;
                SignUpButton.Visibility = Visibility.Visible;
                SignInButton.Visibility = Visibility.Visible;
                ShareIcon.Visibility = Visibility.Collapsed;
                ShareText.Visibility = Visibility.Collapsed;
                CheckSubmIcon.Visibility = Visibility.Collapsed;
                CheckSubmText.Visibility = Visibility.Collapsed;
                ProfileIcon.Visibility = Visibility.Collapsed;
                ViewProfileText.Visibility = Visibility.Collapsed;
                SignOutText.Visibility = Visibility.Collapsed;
            }
            else
            {
                ShareIcon.Visibility = Visibility.Visible;
                ShareText.Visibility = Visibility.Visible;
                CheckSubmIcon.Visibility = Visibility.Visible;
                CheckSubmText.Visibility = Visibility.Visible;
                ProfileIcon.Visibility = Visibility.Visible;
                ViewProfileText.Visibility = Visibility.Visible;
                SignOutText.Visibility = Visibility.Visible;
                SignInText.Visibility = Visibility.Collapsed;
                SignUpButton.Visibility = Visibility.Collapsed;
                SignInButton.Visibility = Visibility.Collapsed;
            }
        }
        #endregion

        #region DatabaseQueryFunction
        private const string strConnectionString = @"isostore:/protoDataContext.sdf";
        private void CreateDatabase()
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                if (database.DatabaseExists() == false)
                {
                    database.CreateDatabase();
                    MessageBox.Show("Database Created Successfully!!!");
                }
                else
                {
                    MessageBox.Show("Database already exists!!!");
                }
            }
        }

        private void AddNewRecord(Project p)
        {
            if (p.getName().Length == 0)
            {
                MessageBox.Show("null!");
                return;
            }
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                ProjectTable newProject = new ProjectTable(
                    p.getId(),
                    p.getAuthorId(),
                    p.getName(),
                    p.getStatus(),
                    p.getDescription(),
                    p.getKeywords(),
                    p.getCreateDate(),
                    p.getLastModifiedDate()
                    );
                database.Projects.InsertOnSubmit(newProject);
                try
                {
                    database.SubmitChanges();
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1);
                    // Make some adjustments.
                    // ...
                    // Try again.
                    database.SubmitChanges();
                }
                MessageBox.Show("Employee Added Successfully!!!");
            }
        }

        private void ListAllProjectRecords()
        {
            IList<ProjectTable> PjtList = null;
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<ProjectTable> query = from pjt in database.Projects select pjt;
                PjtList = query.ToList();
            }
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.AppendLine("Project List");
            foreach (ProjectTable pt in PjtList)
            {
                strBuilder.AppendLine("Name - " + pt.ProjectName + " Created On - " + pt.ProjectCreateDate.ToString());
            }
            MessageBox.Show(strBuilder.ToString());
        }

        private void DeleteRecord(Project p)
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<ProjectTable> query = from pjt in database.Projects where pjt.ProjectId == p.getId() select pjt;
                ProjectTable PjtToRemove = query.FirstOrDefault();
                database.Projects.DeleteOnSubmit(PjtToRemove);
                database.SubmitChanges();
                MessageBox.Show("Project Deleted Successfully!!!");
            }
        }

        private void DeleteDatabase(object sender, RoutedEventArgs e)
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                if (database.DatabaseExists())
                {
                    database.DeleteDatabase();
                    MessageBox.Show("Database Deleted Successfully!!!");
                }
            }
        }
        #endregion

        private void MenuItemQuit_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Menu item 1 works!");
            throw new Exception();
        }

        private void SignInPressed(object sender, RoutedEventArgs e)
        {
            SignedIn = true;
            //Refresh the view
            Refresh();
        }
        private void SignOutAction(object sender, RoutedEventArgs e)
        {
            SignedIn = false;
            //Refresh the view
            Refresh();
        }
        
        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            ProtoProject.PopupCotainer pc = new ProtoProject.PopupCotainer(this);
            pc.Show(new ProtoProject.NewProjectPopup());
            //NavigationService.Navigate(new Uri("/ProtoProject/NewProject.xaml", UriKind.Relative));
        }

        private void Remove_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.ProjectListBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            ItemViewModel itemToDelete = selectedListBoxItem.DataContext as ItemViewModel;
            DeleteSelected(MyProjects, itemToDelete.ItemID);
            Refresh();
        }

        // Handle selection changed on ListBox
        private void ProjectListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (ProjectListBox.SelectedIndex == -1)
                return;
            // Navigate to the new page
            //NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + ProjectListBox.SelectedIndex, UriKind.Relative));
            NavigationService.Navigate(new Uri("/ProtoProject/ViewProject.xaml?selectedItem=" + ProjectListBox.SelectedIndex, UriKind.Relative));
            // Reset selected index to -1 (no selection)
            ProjectListBox.SelectedIndex = -1;
        }

        private void SearchProject_Click(object sender, RoutedEventArgs e)
        {
            //xxxxtesting
            NavigationService.Navigate(new Uri("/ProtoPage/PageView.xaml?selectedPage=0", UriKind.Relative));
        }
    }
}